﻿namespace Dapper.Sharding
{
    internal class OracleUnion : IUnion
    {
        public OracleUnion(IDatabase db) : base(db)
        {
        }

        public OracleUnion(IDatabase db, string sql) : base(db, sql)
        {
        }

        public override string Sql()
        {
            if (string.IsNullOrEmpty(returnFields))
            {
                returnFields = "*";
            }

            if (take == 0)
            {
                return $"SELECT{distinct} {returnFields} FROM ({sqlTable}) UTable{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}{sqlOrderBy}";
            }
            else
            {
                return $"SELECT{distinct} * FROM(SELECT AA.*,rownum rn FROM(SELECT {returnFields} FROM ({sqlTable}) UTable{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}{sqlOrderBy}) AA WHERE rownum<={skip + take}) BB WHERE rn>={skip + 1}";
            }
        }

        public override string SqlCount()
        {
            return $"SELECT COUNT(1) FROM ({sqlTable}) UTable{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}";
        }

        #region aggregate

        public override string SqlExists()
        {
            return $"SELECT 1 FROM {sqlTable}{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}{sqlOrderBy} AND rownum=1";
        }

        public override string SqlMin(string field)
        {
            return $"SELECT MIN({field}) FROM {sqlTable}{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}";
        }

        public override string SqlMax(string field)
        {
            return $"SELECT MAX({field}) FROM {sqlTable}{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}";
        }

        public override string SqlSum(string field)
        {
            return $"SELECT SUM({field}) FROM {sqlTable}{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}";
        }

        public override string SqlAvg(string field)
        {
            return $"SELECT AVG({field}) FROM {sqlTable}{sqlWhere}{sbWhere}{sqlGroupBy}{sqlHaving}";
        }

        #endregion
    }
}
